<?php

require_once 'Spiders/LIB_mail.php';
require_once 'Tools/network.php';

define("ENABLE_LOG", 1);
define("ENABLE_LOG_MAIL", 0);
define("LOG_DIR", dirname(__FILE__) . '/../../log');

function getLogLevel() {
	//ERROR=0
	//LOG=1
	return isset($_GET['forcelog']) ? 1 : 0;
}

function LogItemInfo($itemId, $msg) {
	LogInfo("[itemId=$itemId] $msg");
}

function LogCat($category, $msg, $tag = LOG_PREFIX) {
    if(!ENABLE_LOG) {
        return;
    }	
    
    $prefixdir = date("Y/m");
	$prefix = date("Y-m-d");
	if (!is_dir(LOG_DIR . "/$tag/$prefixdir")) {
		mkdir(LOG_DIR . "/$tag/$prefixdir", 0777, true);
	}
    $myFile = LOG_DIR . "/$tag/$prefixdir/$prefix.log";
    $fh = fopen($myFile, 'a') or die("can't open file");
    $msgs = preg_split("/\n/", $msg);
	$ip = getClientIP();
	$displayIp = ($_SERVER['SERVER_ADDR'] != $ip);
    foreach($msgs as $msg) {
		if($displayIp)
			fwrite($fh, date("H:i:s") . " [$category][ip:$ip] $msg \n");
		else
			fwrite($fh, date("H:i:s") . " [$category] $msg \n");
    }
    fclose($fh);
}

function LogForceInfo($msg, $tag = LOG_PREFIX) {
	LogCat('INFO ', $msg, $tag);
}

function LogInfo($msg, $tag = LOG_PREFIX) {
	if(getLogLevel() > 0)
		LogCat('INFO ', $msg, $tag);
}

function LogError($msg, $tag = LOG_PREFIX) {
	LogCat('ERROR', $msg, $tag);

    if(ENABLE_LOG_MAIL !== 0) {
		$server = LOG_PREFIX;
        $subject = "Error on $server@" . $_SERVER["SERVER_NAME"];
        $message = $msg;
        $address['to'] = "mohamed.elouadi@gmail.com";
        $address['from'] =  "$server@" . $_SERVER["SERVER_NAME"];
        $content_type = "Text/plain";
        formatted_mail($subject, $message, $address, $content_type);
    }
}
?>
